# coding:utf-8
from django.db import transaction
from rest_framework.exceptions import ValidationError

from MSB_ERP.utils.get_inventory import get_inventory
from purchase_info.models import PurchaseModel, PurchaseItemModel
from rest_framework import serializers



class PurchaseItemSerializer(serializers.ModelSerializer):
    #采购下面得到序列化

    class Meta:
        model = PurchaseItemModel
        fields = '__all__'

class PurchaseSerializer(serializers.ModelSerializer):
    """
    新增和修改采购订单序列化和反序列化
    """
    item_list=PurchaseItemSerializer(many=True,write_only=True)
    #采购订单列表在需要展示：商品信息，多个商品的名字+规格，中间用逗号隔开
    goods_info=serializers.SerializerMethodField(read_only=True)


    class Meta:
        model = PurchaseModel
        fields = '__all__'





    def get_goods_info(self,obj):
        #商品信息是：商品名字+商品规格
        if obj.item_list.all():
            reuslt=[]
            for item in obj.item_list.all():
                reuslt.append(item.name + (item.specification if item.specification else ''))
            return ','.join(reuslt)#把列表元素展开用,隔开
        return ''





    def create(self, validated_data):
        item_list=validated_data.pop('item_list')
        with transaction.atomic():
            purchase=PurchaseModel.objects.create(**validated_data)
            for item in item_list:

                pim=PurchaseItemModel.objects.create(purchase=purchase,**item)
                goods=item.get('goods')
                pim.name=goods.name
                pim.specification=goods.specification
                pim.number_code=goods.number_code
                pim.save()


        return purchase

    def update(self, instance, validated_data):

        if instance.status != '0':
            raise ValidationError('采购订单已经生效')
        item_list=validated_data.pop('item_list')
        with transaction.atomic():##把下面的代码封装成事务
            #是否把之前的老数据删除（之前新增的采购订单项目下面数据
            old_list=instance.item_list.all()

            if old_list.exists():#列表是否有数据
                #把之前的数据删除

                    old_list.detele()

            for item in item_list:
                pim=PurchaseItemModel.objects.create(purchase=instance, **item)#修改采购单中的货品（采购项）
                goods = item.get('goods')
                pim.name = goods.name
                pim.specification = goods.specification
                pim.number_code = goods.number_code
                pim.save()

            result=super(PurchaseSerializer,self).update(instance=instance,validated_data=validated_data)#修改采购单
        return result

class PurchaseGetSerializer(serializers.ModelSerializer):
    #仅用于单个采购订单的序列化器

    item_list = serializers.SerializerMethodField(read_only=True)
    class Meta:
        model = PurchaseModel
        fields = '__all__'

    def get_item_list(self,obj):
        result=[] #返回的列表，列表里是多个字典
        if obj.item_list.all().exists():
            for item in obj.item_list.all():#item是一个PurchaseItemModel对象
                #有一部分信息在PurchaseItemModel里面没有
                #只有在GoodsModel有，颜色，型号，单位
                item_dict={}
                goods=item.goods
                item_dict['goods']=goods.id
                item_dict['name']=goods.name
                item_dict['number_code'] = goods.number_code
                item_dict['specification'] = goods.specification
                item_dict['model_number'] = goods.model_number
                item_dict['color'] = goods.color
                item_dict['units'] = goods.units.basic_name
                item_dict['purchase_count'] = item.purchase_count
                item_dict['purchase_price'] = item.purchase_price
                item_dict['purchase_money'] = item.purchase_money
                item_dict['remark'] = item.remark
                #商品的库存数量
                item_dict['cur_inventory'] = get_inventory(goods.id)
                result.append(item_dict)
        return result

























